package com.veetao.api.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class IoUtils {

	public static void writeToFile(String filePath, String pageContent) {
		try {
			//filePath = filePath.replaceAll("\\/", File.separator);
			File f = new File(filePath);
			String path = f.getParent() + File.separator;
			createDirIfNotExists(path);
			if(!f.exists()) {
				f.createNewFile();
			}
			FileWriter w = new FileWriter(f);
			w.write(pageContent);
			w.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static void createDirIfNotExists(String path) {
		File f = new File(path);
		if(!f.exists()) {
			f.mkdirs();
		}
	}
	
	public static String readContentFromInputStream(InputStream is,String charsetName) {
		if(is == null) {
			return null;
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int len = 0;
			while((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}
			is.close();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			return os.toString(charsetName);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}


	public static String getFileContentAsString(String file) {
		return getFileContentAsString(file,"UTF-8");
	}
	public static String getFileContentAsString(String file, String encoding) {
		try {
			return readContentFromInputStream(new FileInputStream(file),encoding);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
